package com.wenyu.wenyuyuedu.activity.circle;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.CreateCircleAdater;
import com.wenyu.wenyuyuedu.bean.circle.CreateCircleBean;
import com.wenyu.wenyuyuedu.bean.circle.ShowCircleType;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.CreateCirlceServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.view.NoScrollGridView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.functions.Action1;

/**
 * 书圈中的创建圈子
 */
public class Creation_Circle_Activity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_left;
    private TextView tv_creation_complete;
    private ImageView ivCirclePictru;
    private EditText etCircleCreation;
    private NoScrollGridView createCircleGv;
    private EditText createCircleEt;
    /* 请求码 */
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private String newFilePath;
    private String strpathing;
    private Boolean tag_photo;
    private String bitmapToString;
    private static final String IMGURL = Environment
            .getExternalStorageDirectory() + "/Android/data/com.hang.dialog/";
    /* 照相机缓存头像名称 */
    private static final String IMAGE_FILE_NAME_TEMP = "temp_faceImage.jpg";
    /* 头像名称 */
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    private File file;
    Dialog dialog;
    private Uri imageUri;
    private CreateCircleAdater adater;
    private String token;
    private String circleName;
    private String circleContent;
    private String currentType = "";
    private List<ShowCircleType.InfoBean> info;
    private RxPermissions rxPermissions;
    private Activity activity;
    private ProgressDialog dia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creation__circle);
        StatusBarUtil.setStatusBar(Creation_Circle_Activity.this, R.color.white);
        activity = Creation_Circle_Activity.this;
        rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(true);
        //初始化布局
        tag_photo = false;
        initView();
        request();
    }

    /*
    * 网络请求
    * */
    private void request() {
        CreateCirlceServer createCirlceServer = ApiWrapper.getInstance().create(CreateCirlceServer.class);
        createCirlceServer.getType().enqueue(new Callback<ShowCircleType>() {
            @Override
            public void onResponse(Call<ShowCircleType> call, Response<ShowCircleType> response) {
                ShowCircleType body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        info = body.getInfo();
                        adater.addAll(info);
                    } else if (code == 4000) {
                        MyToast.showToast(Creation_Circle_Activity.this, "系统繁忙，请稍后重试", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<ShowCircleType> call, Throwable t) {
                MyToast.showToast(Creation_Circle_Activity.this, "系统繁忙，请稍后重试", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initView() {
        iv_left = (ImageView) findViewById(R.id.iv_left);
        tv_creation_complete = (TextView) findViewById(R.id.tv_creation_complete);
        ivCirclePictru = (ImageView) findViewById(R.id.iv_circle_pictru);
        etCircleCreation = (EditText) findViewById(R.id.et_circle_creation);
        createCircleGv = (NoScrollGridView) findViewById(R.id.create_circle_gv);
        createCircleEt = (EditText) findViewById(R.id.create_circle_et);
        iv_left.setOnClickListener(this);
        tv_creation_complete.setOnClickListener(this);
        ivCirclePictru.setOnClickListener(this);
        /*gredview的点击事件---选取类型*/
        adater = new CreateCircleAdater(Creation_Circle_Activity.this);
        createCircleGv.setAdapter(adater);
        selectGredViewType();
    }

    private void selectGredViewType() {
        /*gredview的点击事件---选取类型*/
        createCircleGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                currentType = info.get(i).getId();
                adater.getSeletItem(i);
                //adater.notifyDataSetChanged();
                adater.notifyDataSetInvalidated();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_left:
                finish();
                break;
            //完成按钮
            case R.id.tv_creation_complete:
                token = AbSharedUtil.getString(Creation_Circle_Activity.this, SharedConstants.USER_TOKEN);
                circleName = etCircleCreation.getText().toString().trim();
                circleContent = createCircleEt.getText().toString().trim();
                if (TextUtils.isEmpty(token)) {
                    MyToast.showToast(Creation_Circle_Activity.this, "请先登陆", Toast.LENGTH_SHORT);
                } else if (TextUtils.isEmpty(bitmapToString)) {
                    MyToast.showToast(Creation_Circle_Activity.this, "请选择图片", Toast.LENGTH_SHORT);
                } else if (TextUtils.isEmpty(circleName)) {
                    MyToast.showToast(Creation_Circle_Activity.this, "给自己的书圈添加一个名字吧！", Toast.LENGTH_SHORT);
                } else if (TextUtils.isEmpty(circleContent)) {
                    MyToast.showToast(Creation_Circle_Activity.this, "给自己的圈子添加一些内容吧！", Toast.LENGTH_SHORT);
                } else {
                    dia = new ProgressDialog(this);
                    dia.setMessage("创建中，请稍后....");
                    dia.show();
                    CreateCirlceServer createCirlceServer = ApiWrapper.getInstance().create(CreateCirlceServer.class);
                    Call<CreateCircleBean> circle = createCirlceServer.getCircle(bitmapToString, token, currentType, circleName, circleContent);
                    circle.enqueue(new Callback<CreateCircleBean>() {
                        @Override
                        public void onResponse(Call<CreateCircleBean> call, Response<CreateCircleBean> response) {
                            CreateCircleBean body = response.body();
                            if (body != null) {
                                int code = body.getCode();
                                if (code == 1) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "书圈创建成功", Toast.LENGTH_SHORT);
                                    finish();
                                    dia.dismiss();
                                } else if (code == 0) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "登陆失效，请重新登陆", Toast.LENGTH_SHORT);
                                    showLoginDoalog();
                                    dia.dismiss();
                                } else if (code == 4100) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "该圈子名已经存在了！", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4102) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "简介内容不能超过200个！", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4103) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "圈子的名称中不能有空格！", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4105) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "圈子的标题不能超过24个字！", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4107) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "抱歉您的账户被暂时限制了，无法进行此操作", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4108) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "上传图片错误", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 4110) {
                                    MyToast.showToast(Creation_Circle_Activity.this, "系统繁忙导致创建圈子失败，请稍后再试", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<CreateCircleBean> call, Throwable t) {
                            MyToast.showToast(Creation_Circle_Activity.this, "系统繁忙，请稍后再试", Toast.LENGTH_SHORT);
                            dia.dismiss();
                        }
                    });
                }
                break;
            /*选取图片*/
            case R.id.iv_circle_pictru:
                showDialog();
                break;
        }
    }

    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
                null);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    //在布局写好监听属性
    public void on_click(View v) {
        switch (v.getId()) {
            case R.id.openCamera:
                rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                Boolean aBoolean1 = aBoolean;
                                if (aBoolean) {
                                    //打开相机
                                    openCamera();
                                } else {
                                    /*获取权限的dialog*/
                                    gianPermision();
                                }
                            }
                        });
                break;
            case R.id.openPhones:
                openPhones();
                break;
            case R.id.cancel:
                dialog.cancel();
                break;
            default:
                break;
        }
    }

    android.app.AlertDialog adPermision;
    private TextView quxiaoPermision;
    private TextView quedingPermision;

    /*获取权限的dialog*/
    private void gianPermision() {
        adPermision = new android.app.AlertDialog.Builder(activity).create();
        adPermision.show();
        Window window = adPermision.getWindow();
        window.setContentView(R.layout.dailog_permissions);
        quxiaoPermision = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        quedingPermision = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiaoPermision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adPermision.dismiss();
            }
        });
        quedingPermision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                if (Build.VERSION.SDK_INT >= 9) {
                    Uri packageURI = Uri.parse("package:" + activity.getPackageName());
                    intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    activity.startActivity(intent);
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
                    activity.startActivity(intent);
                }
                adPermision.dismiss();
            }
        });
    }

    // 打开相册
    private void openPhones() {
        Intent intent_gallery = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent_gallery
                .setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
        startActivityForResult(intent_gallery,
                IMAGE_REQUEST_CODE);


    }

    // 打开照相机
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            File file = new File(Environment.getExternalStorageDirectory(), "image.jpg");
            if (file != null) {
                 /*获取当前系统的android版本号*/
                int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                Log.e("currentapiVersion", "currentapiVersion====>" + currentapiVersion);
                if (currentapiVersion < 24) {
                    imageUri = Uri.fromFile(file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                } else {
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
                    imageUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                }
            } else {
                Toast.makeText(activity, "文件读取错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(activity, "文件读取错误", Toast.LENGTH_SHORT).show();
        }
    }


    public Uri cropUri = Uri.parse(Environment.getExternalStorageDirectory() + "crop_image.jpeg");

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        cropUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 1080);
        intent.putExtra("outputY", 1080);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }


    private void saveCroppedImage(Bitmap bmp) {
        File file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        Log.e("-nnnnn", newFilePath);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //把bitmap转换成字符串
    public static String bitmapToString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream btString = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, btString);
        byte[] bytes = btString.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    private void initFileName() {
        file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        System.out.println("path---" + file.getAbsolutePath());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //获取图片
        // 结果码不等于取消时候
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:// 打开相册返回

                    startPhotoZoom(data.getData());
                    Uri selectedImage = data.getData();
                    String schene = selectedImage.getScheme();
                /*    if ("file".equals(schene)) {
                        strpathing = selectedImage.getPath();
                        Bitmap bitmap = ImageUtils.getimage(strpathing);
                        saveCroppedImage(bitmap);
                    }*/
                    break;
                case CAMERA_REQUEST_CODE:// 打开相机返回
                    startPhotoZoom(imageUri);
                    break;
                case RESULT_REQUEST_CODE:// 裁剪完成,删除照相机缓存的图片
                    final File tempFile = new File(IMGURL + IMAGE_FILE_NAME_TEMP);
                    if (tempFile.exists()) {
                        tempFile.delete();
                    }
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    ivCirclePictru.setImageBitmap(bitmap);
                    //点击图库选择的保存的图片
                    bitmapToString = bitmapToString(bitmap);
                    dialog.cancel();//关闭dialog
                    break;
            }
        }

    }

    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(Creation_Circle_Activity.this).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Creation_Circle_Activity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }
}
